package com.mew.auc.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mew.auc.annotation.AseEncrypt;
import com.mew.auc.util.AesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

@RestControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice {

    @Autowired
    AesUtil aesUtil;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        Method method = methodParameter.getMethod();
        if(method != null){
            return method.isAnnotationPresent(AseEncrypt.class);
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(o != null) {
            String data;
            if (o instanceof String) {
                data = (String) o;
            } else {
                data = JSON.toJSONString(o, SerializerFeature.DisableCircularReferenceDetect);
            }

            try {
                data = aesUtil.encrypt(data);
                return data;
            } catch (Exception e) {
                e.printStackTrace();
                return o;
            }
        }
        return o;
    }
}
